package endoscopic

import (
	"rongyy/src/app"
	"rongyy/src/middlewares"
	"rongyy/src/models"
)

type MsgTemplate struct {
	models.BaseModel `xorm:"extends"`
	Title            string `xorm:"title" json:"title"`
	Content          string `xorm:"content" json:"content"`
}

func (pm *MsgTemplate) TableName() string {
	return "msg_template"
}

func (pm *MsgTemplate) Insert() error {
	_, err := app.DB().Insert(pm)
	if err != nil {
		middlewares.Logger.Println("ERROR - FollowUp Insert failed ", err)
		return err
	}
	return nil
}

func (pm *MsgTemplate) Update(req *MsgTemplate) error {
	_, err := app.DB().ID(req.Id).Cols("title", "content").Update(req)
	if err != nil {
		middlewares.Logger.Println("ERROR - type Update failed ", err)
		return err
	}
	return nil
}

func (pm *MsgTemplate) SelectById(id int64) (*MsgTemplate, error) {
	am := &MsgTemplate{}
	has, err := app.DB().Where("id = ? ", id).Limit(1).Get(am)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return am, nil
}

func (pm *MsgTemplate) SelectByList(limit int, start int) ([]MsgTemplate, int64, error) {
	data := make([]MsgTemplate, 0)
	s := app.DB().Table("msg_template")
	total, err := s.Limit(limit, limit*start).Desc("created_at").FindAndCount(&data)
	if err != nil {
		return nil, 0, err
	}
	return data, total, nil
}

func (pm *MsgTemplate) SelectByTitle(title string) (*MsgTemplate, error) {
	am := &MsgTemplate{}
	has, err := app.DB().Where("title = ? ", title).Limit(1).Get(am)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return am, nil
}
